<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 顶部状态栏 -->
    <view class="px-6 pt-12 pb-4 flex items-center justify-between border-b border-gray-100">
      <view class="flex items-center">
        <view class="text-blue-500 mr-3" @click="goBack">
          <text class="fas fa-chevron-left"></text>
        </view>
        <view>
          <view class="text-xl font-bold">{{ deviceName }}</view>
          <view class="flex items-center space-x-2 mt-1">
            <view class="w-2 h-2 rounded-full" :class="deviceInfo && deviceInfo.isOnline ? 'bg-green-500' : 'bg-gray-400'"></view>
            <view class="text-xs text-gray-500">{{ deviceInfo && deviceInfo.isOnline ? '已连接' : '离线' }}</view>
          </view>
        </view>
      </view>
      <view class="flex items-center space-x-4">
        <view class="text-gray-400 hover:text-gray-600" @click="goToDeviceSettings">
          <text class="fas fa-cog text-xl"></text>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="flex-1 px-6 py-4 overflow-auto">
      <!-- 当前播放图案 -->
      <view class="relative flex justify-center items-center mb-8">
        <!-- 沙盘轨迹画布 -->
        <view class="w-64 h-64 rounded-full bg-gray-50 flex items-center justify-center relative overflow-hidden border border-gray-200">
          <canvas 
            canvas-id="sandCanvas" 
            class="w-full h-full rounded-full"
            :style="{ width: '256px', height: '256px' }"
          ></canvas>
          <!-- 播放状态遮罩 -->
          <view class="absolute inset-0 bg-black bg-opacity-20 flex items-center justify-center rounded-full">
            <text :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'" class="text-white text-4xl"></text>
          </view>
        </view>
        
        <!-- 环形进度条 -->
        <view class="progress-ring absolute" :style="{ width: '280px', height: '280px' }">
          <canvas 
            canvas-id="progressCanvas" 
            class="progress-canvas"
            :style="{ width: '280px', height: '280px' }"
          ></canvas>
        </view>
      </view>

      <!-- 播放信息 -->
      <view class="text-center mb-8">
        <view class="text-xl font-medium mb-2">{{ currentPatternName || '未选择图案' }}</view>
        <view class="flex justify-center items-center space-x-2 text-sm text-gray-500">
          <text>{{ formatCurrentTime }}</text>
          <text>/</text>
          <text>{{ formatTotalTime }}</text>
        </view>
      </view>

      <!-- 控制按钮 -->
      <view class="flex justify-center items-center space-x-8 mb-8">
        <view class="text-gray-600 hover:text-gray-800" @click="prevButton">
          <text class="fas fa-step-backward text-2xl"></text>
        </view>
        <view 
          class="w-16 h-16 rounded-full bg-blue-500 text-white flex items-center justify-center shadow-lg shadow-blue-200 hover:bg-blue-600 transition-colors"
          @click="playPauseButton"
        >
          <text :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'" class="text-2xl"></text>
        </view>
        <view class="text-gray-600 hover:text-gray-800" @click="nextButton">
          <text class="fas fa-step-forward text-2xl"></text>
        </view>
      </view>

      <!-- 播放控制选项 -->
      <view class="flex justify-center space-x-4">
        <view 
          class="w-12 h-12 rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 transition-colors flex items-center justify-center" 
          @click="playModeButton"
        >
          <text :class="playModes[playModeIndex].icon" class="text-xl"></text>
        </view>
        <view 
          class="w-12 h-12 rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 transition-colors flex items-center justify-center" 
          @click="goToLightControl"
        >
          <text class="fas fa-lightbulb text-xl"></text>
        </view>
        <view 
          class="w-12 h-12 rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 transition-colors flex items-center justify-center" 
          @click="playbackSettingsButton"
        >
          <text class="fas fa-ellipsis-v text-xl"></text>
        </view>
        <view 
          class="w-12 h-12 rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 transition-colors flex items-center justify-center" 
          @click="goToPlaylist"
        >
          <text class="fas fa-list text-xl"></text>
        </view>
      </view>

      <!-- 收藏集 -->
      <view class="mt-8">
        <view class="flex items-center justify-between mb-3">
          <view class="text-base font-semibold">我的收藏集</view>
          <view class="text-sm text-blue-500" @click="goToCollectionManagement">查看全部</view>
        </view>
        <!-- 收藏集横向滚动列表 -->
        <view class="flex space-x-4 overflow-x-auto -mx-6 px-6 pb-2">
          <view 
            v-for="collection in collections" 
            :key="collection._id"
            class="flex-shrink-0 w-28" 
            @click="goToCollectionDetail(collection._id)"
          >
            <view class="w-full aspect-square bg-gray-50 rounded-xl flex flex-col justify-center text-gray-700 mb-2 p-3 border border-gray-100">
              <view class="text-sm font-medium text-left mb-1 leading-tight">{{ collection.collectionName }}</view>
              <view class="text-xs text-gray-500 text-left">{{ collection.patternCount || 0 }}个图案</view>
            </view>
          </view>
          <!-- 默认收藏集（如果没有数据） -->
          <view v-if="collections.length === 0" class="flex-shrink-0 w-28">
            <view class="w-full aspect-square bg-gray-50 rounded-xl flex flex-col justify-center text-gray-700 mb-2 p-3 border border-gray-100">
              <view class="text-sm font-medium text-left mb-1 leading-tight">暂无收藏集</view>
              <view class="text-xs text-gray-500 text-left">去添加图案</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 播放速度控制底部弹窗 -->
    <view 
      v-if="showSpeedControl"
      class="fixed inset-0 bg-black bg-opacity-50 z-40"
      @click="closeSpeedControl"
    >
      <view 
        class="fixed bottom-0 left-0 right-0 bg-white rounded-t-2xl p-6 z-50"
        @click.stop
      >
        <view class="flex justify-between items-center mb-6">
          <view class="text-lg font-medium">播放控制</view>
          <view class="text-gray-400" @click="closeSpeedControl">
            <text class="fas fa-times text-xl"></text>
          </view>
        </view>
        
        <!-- 播放速度设置 -->
        <view class="mb-6">
          <view class="flex justify-between items-center mb-2">
            <text class="text-sm font-medium">播放速度</text>
            <text class="text-sm text-gray-500">{{ speedValue }}%</text>
          </view>
          <slider 
            :value="speedValue" 
            min="50" 
            max="200" 
            @change="onSpeedChange"
            activeColor="#3b82f6"
            backgroundColor="#e5e7eb"
            block-size="20"
          />
          <view class="flex justify-between mt-1 text-xs text-gray-400">
            <text>慢</text>
            <text>快</text>
          </view>
        </view>
        
        <button 
          class="w-full py-3 bg-blue-500 text-white rounded-xl font-medium hover:bg-blue-600 transition-colors"
          @click="saveSpeedSettings"
        >
          保存设置
        </button>
      </view>
    </view>
  </view>
</template>

<script>
  import { deviceApi, patternApi, playlistApi } from '@/api/index.js'

export default {
  name: 'DeviceControl',
  data() {
    return {
      // 设备信息
      deviceId: '',
      deviceName: '',
      deviceInfo: null,
      userId: null,
      
      // 当前播放信息
      currentPattern: null,
      currentPatternName: '',
      currentTime: 0,
      totalTime: 0,
      progress: 0,
      
      // 播放设置弹窗状态
      showSpeedControl: false,
      speedValue: 100,
      
      // 画布相关
      sandCanvasCtx: null,
      progressCanvasCtx: null,
      
      // 播放状态
      isPlaying: false,
      playModeIndex: 0,
      playModes: [
        { icon: 'fas fa-redo-alt', text: '循环模式' },
        { icon: 'fas fa-random', text: '随机' },
        { icon: 'fas fa-redo', text: '单曲循环' }
      ],
      
      // 收藏集数据
      collections: [],
      loading: false
    }
  },
  
  computed: {
    formatCurrentTime() {
      return this.formatTime(this.currentTime)
    },
    
    formatTotalTime() {
      return this.formatTime(this.totalTime)
    }
  },
  
  onLoad(options) {
    this.deviceId = options.deviceId
    this.deviceName = decodeURIComponent(options.deviceName || '设备')
    this.initPage()
  },
  
  onShow() {
    this.loadDeviceInfo()
  },
  
  methods: {
    async initPage() {
      
      this.initCanvas()
      await this.loadDeviceInfo()
      await this.loadCollections()
    },

    async loadDeviceInfo() {
      if (!this.deviceId || !this.userId) return
      
      try {
        const result = await deviceApi.getDeviceDetail(this.deviceId, this.userId)
        if (result.errCode === 0) {
          this.deviceInfo = result.data
          this.currentPattern = result.data.currentPattern
          this.speedValue = result.data.speed || 100
          
          // 更新播放状态
          this.isPlaying = result.data.status === 'playing'
          
          // 如果有当前图案，设置图案名称
          if (this.currentPattern) {
            this.currentPatternName = '星空图案' // 实际应该从图案数据获取
            this.totalTime = 225 // 3:45 的秒数，实际应该从图案数据获取
          }
        }
      } catch (error) {
        console.error('获取设备信息失败:', error)
        uni.showToast({
          title: '获取设备信息失败',
          icon: 'none'
        })
      }
    },

    async loadCollections() {
      if (!this.userId) return
      
      try {
        const result = await collectionApi.getCollectionList(this.userId)
        if (result.errCode === 0) {
          this.collections = result.data.slice(0, 3) // 只显示前3个收藏集
        }
      } catch (error) {
        console.error('获取收藏集失败:', error)
      }
    },

    async playPauseButton() {
      if (!this.deviceId || !this.userId) return
      
      try {
        const action = this.isPlaying ? 'pause' : 'play'
        const result = await deviceApi.controlDevice(
          this.deviceId, 
          this.userId, 
          action, 
          this.currentPattern
        )
        
        if (result.errCode === 0) {
          this.isPlaying = !this.isPlaying
          uni.showToast({
            title: this.isPlaying ? '开始播放' : '暂停播放',
            icon: 'success',
            duration: 1500
          })
        } else {
          uni.showToast({
            title: result.errMsg || '操作失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('播放控制失败:', error)
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
    },

    async prevButton() {
      // TODO: 实现上一首功能，需要与播放列表结合
      uni.showToast({
        title: '上一首',
        icon: 'none'
      })
    },

    async nextButton() {
      // TODO: 实现下一首功能，需要与播放列表结合  
      uni.showToast({
        title: '下一首', 
        icon: 'none'
      })
    },

    formatTime(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins}:${secs.toString().padStart(2, '0')}`
    },

    initCanvas() {
      // 初始化画布
      this.$nextTick(() => {
        this.sandCanvasCtx = uni.createCanvasContext('sandCanvas', this)
        this.progressCanvasCtx = uni.createCanvasContext('progressCanvas', this)
      })
    },

    // 页面跳转方法
    goBack() {
      uni.navigateBack()
    },
    
    goToDeviceSettings() {
      uni.navigateTo({
        url: `/pages/device/settings?deviceId=${this.deviceId}`
      })
    },
    
    goToLightControl() {
      uni.navigateTo({
        url: `/pages/light/control?deviceId=${this.deviceId}`
      })
    },
    
    goToPlaylist() {
      uni.navigateTo({
        url: `/pages/playlist/index?deviceId=${this.deviceId}`
      })
    },
    
    goToCollectionManagement() {
      uni.navigateTo({
        url: '/pages/collection/management'
      })
    },
    
    goToCollectionDetail(collectionId) {
      uni.navigateTo({
        url: `/pages/collection/detail?id=${collectionId}`
      })
    },

    // 播放模式切换
    playModeButton() {
      this.playModeIndex = (this.playModeIndex + 1) % this.playModes.length
      uni.showToast({
        title: this.playModes[this.playModeIndex].text,
        icon: 'none'
      })
    },

    // 播放设置
    playbackSettingsButton() {
      this.showSpeedControl = true
    },

    closeSpeedControl() {
      this.showSpeedControl = false
    },

    onSpeedChange(e) {
      this.speedValue = e.detail.value
    },

    async saveSpeedSettings() {
      // TODO: 保存播放速度设置到设备
      uni.showToast({
        title: '设置已保存',
        icon: 'success'
      })
      this.closeSpeedControl()
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-50 { background-color: #f9fafb; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-gray-200 { background-color: #e5e7eb; }
.bg-gray-300 { background-color: #d1d5db; }
.bg-gray-400 { background-color: #9ca3af; }
.bg-gray-500 { background-color: #6b7280; }
.bg-green-500 { background-color: #10b981; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-blue-600 { background-color: #2563eb; }

.text-white { color: #ffffff; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-600 { color: #4b5563; }
.text-gray-700 { color: #374151; }
.text-blue-500 { color: #3b82f6; }

.text-xs { font-size: 24rpx; }
.text-sm { font-size: 28rpx; }
.text-base { font-size: 32rpx; }
.text-lg { font-size: 36rpx; }
.text-xl { font-size: 40rpx; }
.text-2xl { font-size: 48rpx; }
.text-4xl { font-size: 72rpx; }

.font-bold { font-weight: 700; }
.font-semibold { font-weight: 600; }
.font-medium { font-weight: 500; }

.h-screen { height: 100vh; }
.h-2 { height: 16rpx; }
.h-12 { height: 96rpx; }
.h-16 { height: 128rpx; }
.h-64 { height: 512rpx; }

.w-2 { width: 16rpx; }
.w-12 { width: 96rpx; }
.w-16 { width: 128rpx; }
.w-28 { width: 224rpx; }
.w-64 { width: 512rpx; }
.w-full { width: 100%; }

.p-3 { padding: 24rpx; }
.p-4 { padding: 32rpx; }
.p-6 { padding: 48rpx; }
.px-6 { padding-left: 48rpx; padding-right: 48rpx; }
.py-3 { padding-top: 24rpx; padding-bottom: 24rpx; }
.py-4 { padding-top: 32rpx; padding-bottom: 32rpx; }
.pt-12 { padding-top: 96rpx; }
.pb-2 { padding-bottom: 16rpx; }
.pb-4 { padding-bottom: 32rpx; }
.mr-3 { margin-right: 24rpx; }
.mb-2 { margin-bottom: 16rpx; }
.mb-3 { margin-bottom: 24rpx; }
.mb-6 { margin-bottom: 48rpx; }
.mb-8 { margin-bottom: 64rpx; }
.mt-1 { margin-top: 8rpx; }
.mt-8 { margin-top: 64rpx; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }
.flex-shrink-0 { flex-shrink: 0; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.space-x-2 > * + * { margin-left: 16rpx; }
.space-x-3 > * + * { margin-left: 24rpx; }
.space-x-4 > * + * { margin-left: 32rpx; }
.space-x-8 > * + * { margin-left: 64rpx; }

.rounded-full { border-radius: 50%; }
.rounded-xl { border-radius: 24rpx; }
.rounded-t-2xl { border-top-left-radius: 32rpx; border-top-right-radius: 32rpx; }

.border { border-width: 1px; }
.border-b { border-bottom-width: 1px; }
.border-gray-100 { border-color: #f3f4f6; }
.border-gray-200 { border-color: #e5e7eb; }

.shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); }
.shadow-blue-200 { box-shadow: 0 10px 15px -3px rgba(147, 197, 253, 0.1), 0 4px 6px -2px rgba(147, 197, 253, 0.05); }

.overflow-auto { overflow: auto; }
.overflow-x-auto { overflow-x: auto; }
.overflow-hidden { overflow: hidden; }

.fixed { position: fixed; }
.absolute { position: absolute; }
.relative { position: relative; }
.inset-0 { top: 0; right: 0; bottom: 0; left: 0; }
.z-40 { z-index: 40; }
.z-50 { z-index: 50; }

.bg-opacity-20 { background-color: rgba(0, 0, 0, 0.2); }
.bg-opacity-50 { background-color: rgba(0, 0, 0, 0.5); }

.aspect-square { aspect-ratio: 1; }
.leading-tight { line-height: 1.25; }
.text-left { text-align: left; }
.text-center { text-align: center; }

.transition-colors { transition-property: background-color, border-color, color, fill, stroke; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; }

.-mx-6 { margin-left: -48rpx; margin-right: -48rpx; }

.hover\:bg-gray-200:hover { background-color: #e5e7eb; }
.hover\:bg-gray-600:hover { background-color: #4b5563; }
.hover\:bg-blue-600:hover { background-color: #2563eb; }
.hover\:text-gray-600:hover { color: #4b5563; }
.hover\:text-gray-800:hover { color: #1f2937; }
</style>
